package com.wasai.action;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ModelDriven;
import com.wasai.domain.User;
import com.wasai.service.UserService;
import com.wasai.util.ConstString;

/**
 * 
 * @author Yiming
 * 
 */
@SuppressWarnings("serial")
@Controller
@Scope("prototype")
public class AccountAction extends BaseAction implements ModelDriven<User> {

	/**
	 * user.
	 */
	private User user = new User();

	/**
	 * User Service.
	 */
	@Resource
	private UserService userService;

	/**
	 * @return
	 */
	@Override
	public final User getModel() {
		return this.user;
	}

	/**
	 * 
	 * @return
	 */
	@Action(value = "/account/login", results = {
			@Result(location = "/user/detail", type = "redirect", name = "success", params = {
					"id", "${model.id}" }),
			@Result(location = "account.login", type = "tiles", name = "input") })
	public final String login() {
		if ((this.user == null) || (this.user.getEmail() == null)) {
			return INPUT;
		}
		boolean result = this.userService.checkLoginUser(this.user);
		if (result) {
			this.user = this.userService.getUserByEmail(this.user.getEmail());
			ServletActionContext.getRequest().getSession()
					.setAttribute(ConstString.CURRENT_USER, this.user);
			return SUCCESS;
		} else {
			return INPUT;
		}
	}

	/**
	 * 
	 * @return
	 */
	@Action(value = "/account/logout", results = { @Result(location = "index", type = "tiles") })
	public final String logout() {
		ServletActionContext.getRequest().getSession()
				.removeAttribute(ConstString.CURRENT_USER);
		return SUCCESS;
	}

	/**
	 * 
	 * @return
	 */
	@Action(value = "/account/signup", results = {
			@Result(location = "/user/detail", type = "redirect", name = "success", params = {
					"id", "${model.id}" }),
			@Result(location = "account.signup", type = "tiles", name = "input") })
	public final String signup() {
		if (this.user.getEmail() == null) {
			return INPUT;
		}
		boolean result = this.userService.signup(this.user);
		if (result) {
			ServletActionContext.getRequest().getSession()
					.setAttribute(ConstString.CURRENT_USER, this.user);
			return SUCCESS;
		} else {
			return INPUT;
		}
	}

}
